package goodmemo.server.resources;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import goodmemo.server.MemoEntry;
import goodmemo.server.MemoEntries;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import java.util.List;
import java.util.ArrayList;
import goodmemo.server.Config;

@Path("getmemo")
public class GetMemoResources {
    @Context ServletContext context;

    private static Logger log = Logger.getLogger(GetMemoResources.class);

    @Path("{receiver}")
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public MemoEntries downloadMemo(@PathParam("receiver") String rcvr){
        log.debug("[downloadMemo] incoming receiver: " + rcvr);

        Connection conn = null;
        Statement stmt = null;
        PreparedStatement pstmt = null;
        ResultSet r = null;

        List<MemoEntry> memoList = new ArrayList<MemoEntry>();
        log.debug("-----------");

        try {
            Config conf = Config.getInstance(context);
            DataSource dataSource = conf.getDataSource();
            conn = dataSource.getConnection();

            String query="SELECT memoid,sender,memo,mtime FROM memoview WHERE receiver=? ORDER BY mtime";
            pstmt = conn.prepareStatement(query);  
            long rcvrLong =Long.parseLong(rcvr);
            log.debug(rcvrLong);
            pstmt.setLong(1,rcvrLong);

            r = pstmt.executeQuery();

            

            while(r.next()){
                long memoid = r.getLong(1);
                long sender = r.getLong(2);
                String memo = r.getString(3);
                long mtime = r.getLong(4);
                MemoEntry me = 
                    new MemoEntry(memoid,sender,memo,mtime); 

                memoList.add(me);
                log.info(me);
            }

        }catch(Exception e) {
            log.error("db error",e);
        }
        finally{
            if (conn != null) {
                try{conn.close();}catch(Throwable e){}
            } 
        }

        return new MemoEntries(memoList);
    }
    
}
